package User;

import javax.swing.*;
import java.sql.*;

public class UserLogin {
    Connection connection = null;
    PreparedStatement prepare = null;
    ResultSet resultSet = null;
    boolean loginSuccess = false;

    public UserLogin() throws SQLException, ClassNotFoundException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://mysql.sqlpub.com:3306/ai_text?useSSL=false&serverTimezone=UTC";
            String username = "root_jin";
            String password = "PYdB6vd981yvuLhD";
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细的异常信息
            JOptionPane.showMessageDialog(null, "数据库连接失败", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    public void readLogin(Login login) {
        try {
            String sql = "SELECT * FROM users WHERE userName = ? AND password = ?";
            prepare = connection.prepareStatement(sql);
            prepare.setString(1, login.getUserName());
            prepare.setString(2, login.getPassword());
            resultSet = prepare.executeQuery();
            if (resultSet.next()) {
                login.setLoginSuccess(true);
                JOptionPane.showMessageDialog(null, "登录成功");
            } else {
                login.setLoginSuccess(false);
                if (login.getUserName().isEmpty() || login.getPassword().isEmpty()) {
                    if (login.getUserName().isEmpty()) {
                        JOptionPane.showMessageDialog(null, "用户名不能为空！", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                    if (login.getPassword().isEmpty()) {
                        JOptionPane.showMessageDialog(null, "密码不能为空！", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "登录失败", "警告", JOptionPane.ERROR_MESSAGE);
                }
            }
            loginSuccess = login.isLoginSuccess();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "异常", "警告", JOptionPane.ERROR_MESSAGE);
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                if (prepare != null) prepare.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
